//
//  HLiveController.m
//  linktuIOS
//
//  Created by hejunsong on 2017/2/5.
//  Copyright © 2017年 tianxie. All rights reserved.
//

#import "HLiveController.h"
#import "MTLiveManagerListController.h"
//PLStream  推流
#import <PLPlayerKit/PLPlayerKit.h>
#import <PLRTCStreamingKit/PLRTCStreamingKit.h>


//view
//model
#import "giftModel.h"

//tool
#import "HMessageTool.h"

//viewModel
#import "HViewerInfoViewModel.h"
#import "HGiftViewModel.h"
#import "HMessageViewModel.h"
#import "HBalanceViewModel.h"


//#import "MTProfileViewController.h"

#import "MTLiveApiManager.h"


#define enableBackgroundPlay    1
#define kReloadConfigurationEnable  1

// 假设在 videoFPS 低于预期 50% 的情况下就触发降低推流质量的操作，这里的 40% 是一个假定数值，你可以更改数值来尝试不同的策略
#define kMaxVideoFPSPercent 0.4

// 假设当 videoFPS 在 10s 内与设定的 fps 相差都小于 5% 时，就尝试调高编码质量
#define kMinVideoFPSPercent 0.05
#define kHigherQualityTimeInterval  8


@interface HLiveController ()
<PLMediaStreamingSessionDelegate,
PLPlayerDelegate,
HLiveSendGiftViewDelegate,
HReplayProgressViewDelagate,
HLiveFinishViewDelegate,
HLiveShareViewDelegate,
HLiveProfileViewDelegate,
HLiveTopAudienceViewDelegate,
HLiveLeftAudienceViewDelegate,
HLiveToolViewDelegate,
HLiveInputViewDelegate,
HLiveMessageViewDelegate,
HLivegoldViewDeleagte,
LTChatManagerDelegate,
MTLiveFunctionViewDelegate,
MTLiveProfileViewDelegate,
MTCreateLiveViewDelegate,
MTBeautifySetViewDelegate>


//viewModel
@property(nonatomic,strong) HViewerInfoViewModel *viewerInfoViewModel;
@property(nonatomic,strong) HGiftViewModel  *giftViewModel;
@property(nonatomic,strong) HMessageViewModel *messageViewModel;
@property(nonatomic,strong) HBalanceViewModel   *balanceViewModel;
@property (nonatomic,assign) NSInteger LightCountNumber;


//拉流
//@property (nonatomic, strong) Reachability *internetReachability;
@property (nonatomic, strong) dispatch_queue_t  sessionQueue;
@property (nonatomic,strong)  NSDate            *keyTime;


@property(nonatomic,strong)  NSTimer  *refreshTimer;    //数据刷新定时器
@property(nonatomic,strong)  NSTimer  *hostonAirTimer;    //主播在线时长timer
@property(nonatomic,assign)  BOOL     isrefreshRoomData;
@property(nonatomic,strong)  NSTimer  *replayTimer;     //回放进度条定时器
@property(nonatomic,assign)  BOOL      isFristLight;      //第一次发送点亮消息
@property (nonatomic,assign) NSTimeInterval startTime;
@property (nonatomic,strong) NSString       *hostLivefromMoney;   //主播开播前的金币
@property (nonatomic,strong) NSString       *hostTotalMoney;   //主播的金币
@property (nonatomic ,assign)NSInteger timesLowerThan10FPS;   //卡顿连续次数
//连麦


//game isGame
//管理员， 黑名单
@property (nonatomic, assign)BOOL isAdmin;
@property (nonatomic, assign)BOOL isInBlackList;

@property (nonatomic, strong) PLMediaStreamingSession *session;

@property (nonatomic, strong) PLPlayer  *player;


@property (nonatomic, assign) BOOL anchorClose;

@end

@implementation HLiveController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:[UIView new]];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [self setDelegate];
    [self bindingViewModel];
    self.anchorprofileView.anchorModel = self.livemodel.anchor;
    
    switch (self.conteollerType) {
        case LiveControllertypeLive:
        {
            [self pushStream];
            self.toolView.style = HLiveToolViewstyleanchor;
        } break;
        case LiveControllertypeAudience:
        {
            self.toolView.style = HLiveToolViewstylaudiences;
            [self joinRoom];
            [self judgeFollowhost];
            //礼物列表
            [self.giftViewModel refreshGiftsuccess:^(BOOL success) {
                [self.giftView relaodData];
            }];
        } break;
        case LiveControllertypeReplay:
        {
            [self joinRoom];
            [self judgeFollowhost];
            //礼物列表
            [self.giftViewModel refreshGiftsuccess:^(BOOL success) {
                [self.giftView relaodData];
            }];
            self.replayTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(replayTimerClcik) userInfo:nil repeats:YES];
        } break;
        default:  break;
    }
    
    [self.balanceViewModel BalanceMoneyRefresh:^(BOOL result) {
    }];
    
    [self.viewerInfoViewModel refresh:self.roomid success:^(BOOL success) {
        [self.topAudicenceView relaodData];
    }];
    [self initMessage];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mtLiveProfileViewCnacelMite:) name:@"mtLiveProfileViewCnacelMite" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mtLiveProfileViewMite:) name:@"mtLiveProfileViewMite" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mtLiveProfileViewMite:) name:@"mtLiveProfileViewMite" object:nil];
    
}

-(void)timerRefresh
{
    [self.balanceViewModel BalanceMoneyRefresh:^(BOOL result) {
    }];
    [self.viewerInfoViewModel refresh:self.roomid success:^(BOOL success) {
        [self.topAudicenceView relaodData];
    }];
}

-(void)setLivemodel:(MTLiveModel *)livemodel
{
    [super setLivemodel:livemodel];
    if(livemodel.replay)
    {
        self.conteollerType = LiveControllertypeReplay;
        self.replayProgressView.hidden = NO;
    }else
    {
        self.conteollerType = LiveControllertypeAudience;
         self.replayProgressView.hidden = YES;
    }
    [self.finishView removeFromSuperview];
    self.anchorprofileView.anchorModel = livemodel.anchor;
    self.giftView.liveModel = livemodel;
    self.roomid = self.livemodel.Id;
    self.chatRoomid = self.livemodel.chatRoomId;
    self.AnchorUserid = self.livemodel.anchor.userId;
    self.userDetailView.masterUserId = self.AnchorUserid;
    self.userDetailView.liveId = self.livemodel.Id;
}



-(void)setLivesArray:(NSMutableArray *)livesArray
{
    _livesArray = livesArray;
    if(livesArray.count > 1)
    {
        self.allowSlideSwitch = YES;
    }
}

-(void)joinRoom
{
    [[MTLiveApiManager manager] joinLive:self.livemodel.Id completion:^(MTError *error) {
        if(error == nil)
        {
            self.livetitleLable.text = [NSString stringWithFormat:@"直播主题:%@",self.livemodel.title];
            [[LTClient sharedClient].chatManager addDelegate:self];
            LTMessage *message = [LTSDKHelper sendJoinRoomMessageRoomId:self.chatRoomid];
            [self sendMessageWithMessage:message];
            [[BONSTimerQueue shareTimer] addEvent:@selector(timerRefresh) target:self timerWithTimeInterval:8];
        }else if (error.code == 2){
            [self.player stop];
            UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"不能进入该直播间，你在该直播间被管理员拉黑了。" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self CloseRoomClick:nil];
            }];
            [alterVc addAction:action1];
            [self presentViewController:alterVc animated:YES completion:nil];
        }
    }];
    [self pullStream];
}



#pragma mark    主播开创直播
-(void)pushStream
{
    PLVideoCaptureConfiguration *videoCaptureConfiguration = [self.videoCaptureConfigurations lastObject];
    PLAudioCaptureConfiguration *audioCaptureConfiguration = [PLAudioCaptureConfiguration defaultConfiguration];
    PLVideoStreamingConfiguration *videoStreamingConfiguration = [self.videoStreamingConfigurations lastObject];
    PLAudioStreamingConfiguration *audioStreamingConfiguration = [PLAudioStreamingConfiguration defaultConfiguration];
    self.session = [[PLMediaStreamingSession alloc] initWithVideoCaptureConfiguration:videoCaptureConfiguration audioCaptureConfiguration:audioCaptureConfiguration videoStreamingConfiguration:videoStreamingConfiguration audioStreamingConfiguration:audioStreamingConfiguration stream:nil];
    [self.session setBeautifyModeOn:YES];
    [self.session setBeautify:1];
    [self.session setWhiten:1];
    [self.session setRedden:0];
//    [self.session toggleCamera];
    self.session.autoReconnectEnable = YES;
    self.session.delegate = self;
    [self.view addSubview:self.createLiveView];
    [self.createLiveView insertSubview:self.session.previewView atIndex:0];
}


#pragma mark -- POST请求获取pull URL
-(void)pullStream
{
    PLPlayerOption *option = [PLPlayerOption defaultOption];
    [option setOptionValue:@15 forKey:PLPlayerOptionKeyTimeoutIntervalForMediaPackets];
    
    NSURL *url = [NSURL URLWithString:self.livemodel.playUrl];
    if(self.livemodel.replay)
    {
        url = [NSURL URLWithString:self.livemodel.rePlayUrl];
    }
    self.player = [PLPlayer playerLiveWithURL:url option:option];
    self.player.delegate = self;
    [self.view insertSubview:self.player.playerView atIndex:0];
    self.player.playerView.contentMode = UIViewContentModeScaleAspectFill;
    [self.player play];
    [self startAnimation];
}

-(void)setDelegate
{
    self.anchorprofileView.delegate = self;
    self.leftanchorprofileView.delegate = self;
    self.topAudicenceView.delegtae = self;
    self.leftAudicenceView.delegate = self;
    self.toolView.delegate = self;
    self.inputView.delegate = self;
    self.messageView.delegate = self;
    self.goldView.delegate = self;
}


#pragma mark ---------------- viewModel
-(void)bindingViewModel
{
    _viewerInfoViewModel = [[HViewerInfoViewModel alloc] init];
    self.topAudicenceView.viewmodel      = _viewerInfoViewModel;
    self.leftAudicenceView.viewmodel     = _viewerInfoViewModel;
    self.anchorprofileView.viewModel     = _viewerInfoViewModel;
    self.leftanchorprofileView.viewModel = _viewerInfoViewModel;
    
    self.giftViewModel = [[HGiftViewModel alloc] init];
    self.giftView.giftViewModel = _giftViewModel;
    
    self.messageViewModel = [[HMessageViewModel alloc] init];
    self.messageView.messageViewModel = _messageViewModel;
    
    
    //余额绑定  双向绑定  数据变化立马更新view（money）
    self.balanceViewModel = [[HBalanceViewModel alloc] init];
    self.giftView.balanceViewModel = _balanceViewModel;
    self.balanceViewModel.sendGiftView = self.giftView;
    self.inputView.balanceViewModel = _balanceViewModel;
}

-(void)SwitchLiveClick:(UIPanGestureRecognizer *)gesture
{
    CGPoint distanceSource = [gesture translationInView:gesture.view];
    if(fabs(distanceSource.x) < fabs(distanceSource.y))
    {
        self.IsTopgesture = YES;
    }
    if(self.IsTopgesture == YES)
    {
        self.view.y = distanceSource.y;
        if(gesture.state == UIGestureRecognizerStateEnded)
        {
            self.IsTopgesture = NO;
            if(distanceSource.y > 100)
            {
                [UIView animateWithDuration:0.3 animations:^{
                    self.view.y = +HEIGHT;
                } completion:^(BOOL finished) {
                    self.view.y = 0;
                    [self nextLiveModelDirection:NO];
                    [self reloadLiveRoomData];
                }];
            }
            else if(distanceSource.y < -100)
            {
                [UIView animateWithDuration:0.3 animations:^{
                    self.view.y = -HEIGHT;
                } completion:^(BOOL finished) {
                     self.view.y = 0;
                     [self nextLiveModelDirection:YES];
                     [self reloadLiveRoomData];
                }];
            }else
            {
                [UIView animateWithDuration:0.2 animations:^{
                    self.view.y = 0;
                }];
            }
        }
    }
}

/**
 切换直播间的时候更细直播间数据
 */
-(void)reloadLiveRoomData
{
    [self reoladCover];
    NSURL *url = [NSURL URLWithString:self.livemodel.playUrl];
    if(self.livemodel.replay)
    {
        url = [NSURL URLWithString:self.livemodel.rePlayUrl];
    }
    self.currentImageView.hidden = NO;
    [self.player playWithURL:url sameSource:NO];
    [self.messageViewModel.mesageArray removeAllObjects];
    [self.viewerInfoViewModel.viewerModelArray removeAllObjects];
    [self.topAudicenceView relaodData];
    [self initMessage];
}

/**
 切换直播间

 @param direction 方向 yes 顺向 false 反向
 */
-(void)nextLiveModelDirection:(BOOL)direction
{
    //先退当前出房间
    [[MTLiveApiManager manager] quiteLive:self.roomid completion:^(MTError *error) {
    }];
    NSInteger count = self.livesArray.count;
    if(direction == YES)
    {
        if(self.currentIndex < (count - 1))
        {
            self.currentIndex = self.currentIndex + 1;
        }else
        {
            self.currentIndex = 0;
        }
    }else
    {
        if(self.currentIndex == 0)
        {
            self.currentIndex = count - 1;
        }else
        {
            self.currentIndex = self.currentIndex - 1;
        }
    }
    NSInteger bottomIndex = 0;
    if(self.currentIndex < (count -1))
    {
        bottomIndex = self.currentIndex + 1;
    }else
    {
        bottomIndex = 0;
    }
    NSInteger topIndex = 0;
    if(self.currentIndex == 0)
    {
        topIndex = count - 1;
    }else
    {
        topIndex = self.currentIndex - 1;
    }
    self.toplivemodel = self.livesArray[topIndex];
    self.bottomlivemodel = self.livesArray[bottomIndex];
    self.livemodel = self.livesArray[self.currentIndex];
    
    NSLog(@"topindx - %ld currentIndex - %ld  bottomIndex - %ld",topIndex,self.currentIndex,bottomIndex);
    [self judgeFollowhost];
    [[MTLiveApiManager manager] joinLive:self.roomid completion:^(MTError *error) {
    }];
}


-(void)LightClick
{
    [self.inputView resignliveFirstResponder];
    self.LightCountNumber++;
    LTMessage *lightMessage = [LTSDKHelper sendLightUpMessageRoomId:self.chatRoomid isFrist:!_isFristLight];
    [self sendMessageWithMessage:lightMessage];
    if(!_isFristLight) { _isFristLight = YES; }
}

-(void)initMessage
{
    NSString *messageText = NSLTLocalizedString(@"我们提倡绿色直播，封面和直播内容含吸烟、低俗、引诱、暴露等都将会被封停账号。绿色米兔，我们携手共创～", nil);
    LTMessage *message = [LTSDKHelper sendChatRoomNoramlMessage:messageText roomId:self.chatRoomid];
    message.since.name = @"直播消息";
    [self filterMessage:message];
}

-(void)creatPullActonWithURL:(NSString *)pullURL
{
    if(pullURL == nil)
    {
        return;
    }
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    // 初始化 PLPlayerOption 对象
    PLPlayerOption *option = [PLPlayerOption defaultOption];
    // 更改需要修改的 option 属性键所对应的值
    [option setOptionValue:@5 forKey:PLPlayerOptionKeyTimeoutIntervalForMediaPackets];
    [option setOptionValue:@1000 forKey:PLPlayerOptionKeyMaxL1BufferDuration];
    [option setOptionValue:@1000 forKey:PLPlayerOptionKeyMaxL2BufferDuration];
    //[option setOptionValue:@(YES) forKey:PLPlayerOptionKeyVideoToolbox];
    //[option setOptionValue:@(kPLLogInfo) forKey:PLPlayerOptionKeyLogLevel];
    
    // 初始化 PLPlayer
    self.player = [PLPlayer playerWithURL:[NSURL URLWithString:pullURL] option:option];
    // 设定代理 (optional)
    self.player.delegate = self;
    //    self.player.autoReconnectEnable = YES;
    //    self.player.backgroundPlayEnable = enableBackgroundPlay;
    self.player.delegateQueue = dispatch_get_main_queue();
    self.player.playerView.contentMode = UIViewContentModeScaleAspectFit;// self.livecontentMode ;// UIViewContentModeScaleAspectFit;
    self.player.playerView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleTopMargin
    | UIViewAutoresizingFlexibleLeftMargin
    | UIViewAutoresizingFlexibleRightMargin
    | UIViewAutoresizingFlexibleWidth
    | UIViewAutoresizingFlexibleHeight;
    [self.view insertSubview:self.player.playerView atIndex:0];
    [self.player play];
}

#pragma mark  UIButton  Click
-(void)CloseRoomClick:(UIButton *)but
{
    if(self.conteollerType == LiveControllertypeLive)
    {
        UIAlertController *quitVc = [UIAlertController alertControllerWithTitle:NSLTLocalizedString(@"结束本次直播", nil) message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *commplentaction = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.anchorClose = YES;
            LTMessage *message = [LTSDKHelper sendCloseLiveMessageRoomId:self.livemodel.chatRoomId];
            [self sendMessageWithMessage:message];
            [[BONSTimerQueue shareTimer] removeEcvent:@selector(timerRefresh) target:self];
        }];
        UIAlertAction *cancleaction = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [quitVc addAction:commplentaction];
        [quitVc addAction:cancleaction];
        [self presentViewController:quitVc animated:YES completion:nil];
        
    }else if (self.conteollerType == LiveControllertypeAudience)
    {
        [self.player stop];
        self.player = nil;
        [[BONSTimerQueue shareTimer] removeEcvent:@selector(timerRefresh) target:self];
        [[MTLiveApiManager manager] quiteLive:self.livemodel.Id completion:^(MTError *error) {
        }];
        [self.giftView clearTimer];
        [self.replayTimer invalidate];
        self.replayTimer = nil;
        [[LTClient sharedClient].chatManager removeDelegate:self];
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.conteollerType == LiveControllertypeReplay)
    {
        [self.player stop];
        [[MTLiveApiManager manager] quiteLive:self.livemodel.Id completion:^(MTError *error) {
        }];
        self.player = nil;
        [self.replayTimer invalidate];
        self.replayTimer = nil;
        [[LTClient sharedClient].chatManager removeDelegate:self];
        [[BONSTimerQueue shareTimer] removeEcvent:@selector(timerRefresh) target:self];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)cancleAddObserver
{
    [self.mainScrollView removeObserver:self forKeyPath:@"contentSize" context:@"_mainScrollViewID"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark MTCreateLiveViewDelegate
-(void)createLiveView:(MTCreateLiveView *)view liveModel:(MTLiveModel *)liveModel
{
    self.livemodel = liveModel;
    self.conteollerType = LiveControllertypeLive;
    [[LTClient sharedClient].chatManager addDelegate:self];
    [self initMessage];
    self.livetitleLable.text = [NSString stringWithFormat:@"直播主题:%@",liveModel.title];
    [view removeFromSuperview];
    [self.view insertSubview:self.session.previewView atIndex:0];
    NSURL *pushUrl = [NSURL URLWithString:self.livemodel.pushUrl];
    [[BONSTimerQueue shareTimer] addEvent:@selector(timerRefresh) target:self timerWithTimeInterval:8];
    [self.session startStreamingWithPushURL:pushUrl feedback:^(PLStreamStartStateFeedback feedback) {
        if (feedback == PLStreamStartStateSuccess) {
            NSLog(@"Streaming started.");
        }
        else {
            NSLog(@"Oops.");
        }
    }];
}
-(void)createLiveViewClose:(MTCreateLiveView *)view
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)createLiveViewbeautyClick
{
    [self.beautifySetView show];
}

#pragma  mark  HLiveTopAudienceViewDelegate
-(void)topAudienceView:(HLiveTopAudienceView *)view index:(NSInteger)index
{
    LTUser *user = self.viewerInfoViewModel.viewerModelArray[index];
    self.userDetailView.user = user;
    self.userDetailView.masterUserId = self.livemodel.anchor.userId;
    [self.userDetailView showView:self.view];
    
}
#pragma  mark  HLiveLeftAudienceViewDelegate
-(void)leftAudienceView:(HLiveLeftAudienceView *)view index:(NSInteger)index
{
    if(self.conteollerType == LiveControllertypeLive || self.isAdmin)
    {
        
    }else{
        
    }
}
#pragma mark HLiveInputViewDelegate
-(void)hliveInputViewaddMessage:(NSString *)content isBullet:(BOOL)bullet
{
    LTMessage *message = nil;
    if(bullet)
    {
        message = [LTSDKHelper sendChatRoomBarrageMessage:content roomId:self.chatRoomid];
    }else
    {
        message = [LTSDKHelper sendChatRoomNoramlMessage:content roomId:self.chatRoomid];
    }
    [self sendMessageWithMessage:message];
}

#pragma mark MTLiveProfileViewDelegate
-(void)mtLiveProfileViewAtUser:(LTUser *)user
{
    self.inputView.aitaStr = user.name;
    [self.inputView becomeliveFristResponder];
}
-(void)mtLiveProfileViewGoUserHomeUser:(LTUser *)user
{
//    MTProfileViewController *profileVc = [[MTProfileViewController alloc] init];
//    profileVc.userId = user.userId;
//    [self.navigationController pushViewController:profileVc animated:YES];
}
-(void)mtLiveProfileViewSetMamnager:(LTUser *)user
{
    LTMessage *message = [LTSDKHelper sendRoomMessageRoomId:self.chatRoomid operationUser:user messagetype:LTMessageTypeRoomSetManager];
    [self sendMessageWithMessage:message];
}
-(void)mtLiveProfileViewCancelMamnager:(LTUser *)user
{
    LTMessage *message = [LTSDKHelper sendRoomMessageRoomId:self.chatRoomid operationUser:user messagetype:LTMessageTypeRoomCancelManager];
    [self sendMessageWithMessage:message];
}
-(void)mtLiveProfileViewMite:(LTUser *)user
{
    LTMessage *message = [LTSDKHelper sendRoomMessageRoomId:self.chatRoomid operationUser:user messagetype:LTMessageTypeRoomMute];
    [self sendMessageWithMessage:message];
}
-(void)mtLiveProfileViewCnacelMite:(LTUser *)user
{
    LTMessage *message = [LTSDKHelper sendRoomMessageRoomId:self.chatRoomid operationUser:user messagetype:LTMessageTypeRoomCancelMute];
     [self sendMessageWithMessage:message];
}
-(void)mtLiveProfileViewblack:(LTUser *)user
{
    LTMessage *message = [LTSDKHelper sendRoomMessageRoomId:self.chatRoomid operationUser:user messagetype:LTMessageTypeRoomKickout];
    [self sendMessageWithMessage:message];
}


#pragma mark  HLiveSendGiftViewDelegate
-(void)hliveSendGiftViewWithMesage:(LTMessage *)giftMessage
{
    [self sendMessageWithMessage:giftMessage];
}

#pragma mark  HLiveShareViewDelegate
-(void)hliveShareView:(HLiveShareView *)shareView withType:(Sharetype)type
{
    
}

#pragma mark PersonDetailDelegate
-(void)PersonDetailReplayMessage:(NSString *)tousername
{
    self.inputView.aitaStr = tousername;
    [self.inputView becomeliveFristResponder];
}
#pragma mark HLiveProfileViewDelegate
-(void)hliveProfileViewHeaderClcikWithUserID:(NSString *)userID
{
    [[MTUserApiManager manager] getUserInfo:userID completion:^(MTUserModel *user, MTError *mterror) {
       if(mterror == nil)
       {
           LTUser *ltuser = [LTSDKHelper usertransformMTUser:user];
           self.userDetailView.user = ltuser;
           self.userDetailView.ishost = YES;
           self.userDetailView.masterUserId = self.livemodel.anchor.userId;
           [self.userDetailView showView:self.view];
       }
    }];
}
#pragma mark  HLiveMessageViewDelegate
-(void)hliveMessageViewWithuserID:(LTUser *)user
{
    if(user == nil){  return; }
    self.userDetailView.user = user;
    self.userDetailView.masterUserId = self.livemodel.anchor.userId;
    [self.userDetailView showView:self.view];

}
#pragma mark  StopLiveViewDelegate
-(void)stopliveCloseAndSave:(BOOL)save
{
    if(save)
    {
        [[MTLiveApiManager manager] saveLivePlayback:self.roomid completion:^(MTError *error) {
        }];
    }
    [self.session destroy];
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark HLiveFinishViewDelegate
-(void)hlivefinishView:(HLiveFinishView *)finishView withButtonType:(finishedLiveClickType)type
{
    [self.player stop];
    self.player = nil;
    [[BONSTimerQueue shareTimer] removeEcvent:@selector(timerRefresh) target:self];
    [[MTLiveApiManager manager] quiteLive:self.livemodel.Id completion:^(MTError *error) {
    }];
    [self.giftView clearTimer];
    [self.replayTimer invalidate];
    self.replayTimer = nil;
    [[LTClient sharedClient].chatManager removeDelegate:self];
    self.finishView.liveModel = self.livemodel;
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)hlivefinishView:(HLiveFinishView *)finishView withShareType:(Sharetype)type
{
    [[MTUserApiManager manager] followUserV2WithUserId:self.livemodel.anchor.userId follow:YES completion:^(MTError *mterror) {
    }];
    [self hliveShareView:nil withType:type];
}

#pragma mark HLiveToolViewDelegate
-(void)hlivetoolViewsendMessage:(HLiveToolView *)livetoolview;
{
    [[MTUserApiManager manager] getSelfLiveStatusMasterUserId:self.livemodel.anchor.userId completion:^(MTUserModel *user, MTError *mterror) {
       if(mterror == nil)
       {
           self.inputView.isBlack = user.userLiveStatus.isNoSpeaking;
       }
    }];
    [self.inputView becomeliveFristResponder];
}
-(void)hlivetoolViewMusic:(HLiveToolView *)livetoolview
{
    
}
-(void)hlivetoolViewShare:(HLiveToolView *)livetoolview
{
//    [self.shareView show];
}
// no 表示是giftview显示 Yes表示是gameview显示
-(void)hlivetoolViewSendGift:(HLiveToolView *)livetoolview
{
    [self.giftView show];
}

-(void)hlivetoolViewFullScreen:(HLiveToolView *)livetoolview
{
//    self.mainScrollView.hidden = YES;
//    self.closeFullScreenButton.hidden = NO;
    [self CloseRoomClick:nil];
    
}

-(void)hlivetoolViewLink:(HLiveToolView *)livetoolview
{
    if(self.conteollerType == LiveControllertypeAudience)
    {
        
    }
    
    
}
-(void)hlivetoolViewCloseLink:(HLiveToolView *)livetoolview
{
    //       关闭连麦
}
-(void)hlivetoolViewAnchorLinkClick:(HLiveToolView *)livetoolview
{
    
    
}
-(void)hlivetoolView:(HLiveToolView *)livetoolview replayplayorpause:(BOOL)isplay
{
    if(!isplay)
    {
        [self.player play];
    }else
    {
        [self.player pause];
    }
}

-(void)hlivetoolViewShowAnchorSetView:(HLivegoldView *)livetoolview
{
    [self.functionView show];
}

#pragma mark MTLiveFunctionViewDelegate
//开关美颜
-(void)mtLiveFunctionViewBeautifulClick:(BOOL)beautiful
{
//    [self.session setBeautifyModeOn:beautiful];
    [self.functionView dismis];
    [self.beautifySetView show];
}
//分享view
-(void)mtLiveFunctionViewShareClick
{
    [self.functionView dismis];
//    [self.shareView show];
}
//开关闪光
-(BOOL)mtLiveFunctionViewFlashClick:(BOOL)onofff
{
    self.session.torchOn = !self.session.isTorchOn;
    return self.session.torchOn;
}
//摄像头翻转
-(void)mtLiveFunctionViewFlipClick
{
    [self.session toggleCamera];
}
//设置静音
-(BOOL)mtLiveFunctionViewMute:(BOOL)onofff
{
//  self.session.muteMixedAudio = !self.session.muteMixedAudio;
    self.session.muted = !self.session.muted;
    if(self.session.muted)
    {
        [MBProgressHUD showSuccess:@"静音设置成功"];
    }else
    {
        [MBProgressHUD showSuccess:@"取消静音成功"];
    }
    return self.session.muted;
//    return self.session.torchOn;
}
-(void)mtLiveFunctionViewManagerClick
{
     UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *managerListaction = [UIAlertAction actionWithTitle:@"管理员列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MTLiveManagerListController *managerVc = [[MTLiveManagerListController alloc] init];
        managerVc.type = 1;
        managerVc.liveUserId = self.livemodel.anchor.userId;
        managerVc.liveVc = self;
        [self.navigationController pushViewController:managerVc animated:true];
       
    }];
    
    UIAlertAction *blacksListaction = [UIAlertAction actionWithTitle:@"黑名单列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MTLiveManagerListController *managerVc = [[MTLiveManagerListController alloc] init];
        managerVc.type = 2;
         managerVc.liveUserId = self.livemodel.anchor.userId;
         managerVc.liveVc = self;
        [self.navigationController pushViewController:managerVc animated:true];
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *muteListaction = [UIAlertAction actionWithTitle:@"禁言列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MTLiveManagerListController *managerVc = [[MTLiveManagerListController alloc] init];
        managerVc.type = 3;
        managerVc.liveUserId = self.livemodel.anchor.userId;
         managerVc.liveVc = self;
        [self.navigationController pushViewController:managerVc animated:true];
    }];
     [alterVc addAction:managerListaction];
     [alterVc addAction:blacksListaction];
     [alterVc addAction:muteListaction];
     [alterVc addAction:cancleAction];
    
    [self presentViewController:alterVc animated:YES completion:nil];
    
}

//发公告
-(void)mtLiveFunctionViewNoticeClick
{
    [self.functionView dismis];
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"设置直播主题" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    UIAlertAction *action=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
       
        UITextField *tf = alertController.textFields.firstObject;
       if(tf.text.length > 0)
       {
           [[MTLiveApiManager manager] modifyLiveTitleLiveId:self.roomid title:tf.text completion:^(MTError *error) {
              if(error == nil)
              {
                  LTMessage *message = [LTSDKHelper updateRoomTitleMessageRoomId:self.chatRoomid title:tf.text];
                  [self sendMessageWithMessage:message];
              }else
              {
                  [MBProgressHUD showMessage:error.errorDescription];
              }
           }];
       }
    }];
    UIAlertAction *action_cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:action_cancel];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

-(void)mtLiveProfileViewFocusHost
{
    LTMessage *message = [LTSDKHelper focusHostMessageRoomId:self.chatRoomid];
    [self sendMessageWithMessage:message];
}


-(void)beautify:(CGFloat)beautify Red:(CGFloat)red white:(CGFloat)white
{
    [self.session setBeautify:beautify];
    [self.session setWhiten:white];
    [self.session setRedden:red];
}

-(void)replayTimerClcik
{
    if(!self.isDragProgressView){
        self.timeShowOut = _player.currentTime.value / _player.currentTime.timescale;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.replayProgressView.currentTime = self.timeShowOut;
        });
    }
}

#pragma mark
-(void)ReplayProgressViewstratDragSlider
{
    self.isDragProgressView = YES;
    NSLog(@"isDragProgressView");
    
}
-(void)ReplayProgressViewupdateProgress:(CGFloat)secondes
{
    NSLog(@"isDragProgressView-----End，%f",secondes);
    [self.player seekTo:CMTimeMakeWithSeconds(secondes, _player.currentTime.timescale)];
    self.isDragProgressView = NO;
}
-(void)ReplayProgressViewreplayplayorpause:(BOOL)isPlay
{
    if(!isPlay)
    {
        [self.player resume];
    }else
    {
        [self.player pause];
    }
}


#pragma mark - <PLPlayerDelegate>
- (void)player:(nonnull PLPlayer *)player stoppedWithError:(nullable NSError *)error
{
    [[MTLiveApiManager manager] getLiveInfoWithLiveId:self.livemodel.Id completion:^(MTLiveModel *liveModel, MTError *error) {
        if(error == nil)
        {
            
            if(liveModel.status != 1 && liveModel.replay == NO)
            {
//                for (int i = 0; i < self.livesArray.count; i ++) {
//                    MTLiveModel *model = self.livesArray[i];
//                    if([model.Id isEqualToString:liveModel.Id])
//                    {
//                        [self.livesArray removeObjectAtIndex:i];
//                    }
//                }
                
                self.finishView.liveModel = self.livemodel;
                [self.view addSubview:self.finishView];
            }
        }
    }];
//    [self.player play];
    NSLog(@"%@",error);
}

// 实现 <PLPlayerDelegate> 来控制流状态的变更
- (void)player:(nonnull PLPlayer *)player statusDidChange:(PLPlayerStatus)state {
    // 这里会返回流的各种状态，你可以根据状态做 UI 定制及各类其他业务操作
    // 除了 Error 状态，其他状态都会回调这个方法
    self.view.userInteractionEnabled = YES;
    //_state = state;
    if (PLPlayerStatusCaching == state) {
        [self startAnimation];
        self.replayProgressView.isplay = NO;
    }else if(PLPlayerStatusStopped == state){
        [self stopAnimation];
        self.replayProgressView.isplay = NO;
    }else if(PLPlayerStatusPaused == state){
        [self stopAnimation];
        self.replayProgressView.isplay = NO;
    }else if( PLPlayerStatusPlaying == state ){
        if(self.conteollerType == LiveControllertypeReplay)
        {
            self.replayProgressView.totaleTimeScocnd =   _player.totalDuration.value / _player.totalDuration.timescale;
        }
        self.replayProgressView.isplay = YES;
        self.currentImageView.hidden = YES;
        [self stopAnimation];  //成功后关闭加载
    }else if(state == PLPlayerStatusError)
    {
        [MBProgressHUD showMessage:@"主播下播了"];
    }else if (state == PLPlayerStatusCompleted)
    {
         [self stopAnimation];
        [self.player seekTo:CMTimeMakeWithSeconds(0, 0.0)];
        [self.player stop];
    }
}


#pragma mark - <PLStreamingSendingBufferDelegate>

- (void)streamingSessionSendingBufferDidEmpty:(id)session {
    
}
- (void)streamingSessionSendingBufferDidFull:(id)session {
    NSLog(@"Sending buffer full");
    NSString *log = @"Buffer is full";
    NSLog(@"%@", log);
}
- (void)streamingSession:(id)session sendingBufferDidDropItems:(NSArray *)items {
    NSString *log = @"Frame dropped";
    NSLog(@"%@", log);
}

#pragma mark - <PLMediaStreamingSessionDelegate>
/// @abstract 流状态已变更的回调
- (void)mediaStreamingSession:(PLMediaStreamingSession *)session streamStateDidChange:(PLStreamState)state{
    //    NSString *log = [NSString stringWithFormat:@"Stream State: %s", stateNames[state]];
    //    NSLog(@"%@", log);
    
    // 除 PLStreamStateError 外的其余状态会回调在这个方法
    // 这个回调会确保在主线程，所以可以直接对 UI 做操作
    if (PLStreamStateConnected == state) {
        [self stopAnimation];
    } else{
        //[self sendGeneralMessage:@"主播的网络已经坠入深渊，客官稍等片刻"];
        self.timesLowerThan10FPS ++;
        if (self.timesLowerThan10FPS > 5) {
            [self warningHostOut];
        }
    }
}

/// @abstract 因产生了某个 error 而断开时的回调
- (void)mediaStreamingSession:(PLMediaStreamingSession *)session didDisconnectWithError:(NSError *)error{
    NSString *log = [NSString stringWithFormat:@"Stream State: Error. %@", error];
    NSLog(@"%@", log);
    // PLStreamStateError 都会回调在这个方法
    // 尝试重连，注意这里需要你自己来处理重连尝试的次数以及重连的时间间隔
    [self startSession];
    
}
- (void)startSession {
    self.keyTime = nil;
    [self.session restartStreamingWithPushURL:[NSURL URLWithString:self.livemodel.pushUrl] feedback:^(PLStreamStartStateFeedback feedback) {
    }];
}
/// @abstract 当开始推流时，会每间隔 3s 调用该回调方法来反馈该 3s 内的流状态，包括视频帧率、音频帧率、音视频总码率
- (void)mediaStreamingSession:(PLMediaStreamingSession *)session streamStatusDidUpdate:(PLStreamStatus *)status{
    
#if kReloadConfigurationEnable
    NSDate *now = [NSDate date];
    if (!self.keyTime) {
        self.keyTime = now;
    }
    
    double expectedVideoFPS = (double)self.session.videoStreamingConfiguration.expectedSourceVideoFrameRate;
    double realtimeVideoFPS = status.videoFPS;
    NSLog(@"期望值  ==    %lf, 实际值  ======   %lf, 卡顿次数为  %ld", expectedVideoFPS, realtimeVideoFPS, self.timesLowerThan10FPS );
    if (realtimeVideoFPS < 10.0) {
        self.timesLowerThan10FPS ++;
    }else{
        self.timesLowerThan10FPS = 0 ;
    }
    
    if (self.timesLowerThan10FPS > 5) {
        [self warningHostOut];
    }
    if (realtimeVideoFPS < expectedVideoFPS * (1 - kMaxVideoFPSPercent)) {
        // 当得到的 status 中 video fps 比设定的 fps 的 50% 还小时，触发降低推流质量的操作
        self.keyTime = now;
        [self lowerQuality];
    } else if (realtimeVideoFPS >= expectedVideoFPS * (1 - kMinVideoFPSPercent)) {
        if (-[self.keyTime timeIntervalSinceNow] > kHigherQualityTimeInterval) {
            self.keyTime = now;
            [self higherQuality];
        }
    }
#endif  // #if kReloadConfigurationEnable
}

    
- (void)higherQuality {
    NSUInteger idx = [self.videoStreamingConfigurations indexOfObject:self.session.videoStreamingConfiguration];
    NSAssert(idx != NSNotFound, @"Oops");
    
    if (idx >= self.videoStreamingConfigurations.count - 1) {
        return;
    }
    PLVideoStreamingConfiguration *newStreamingConfiguration = self.videoStreamingConfigurations[idx + 1];
    [self.session reloadVideoStreamingConfiguration:newStreamingConfiguration];
    NSLog(@"自动增高了推流质量");
}
    
- (void)lowerQuality {
    NSUInteger idx = [self.videoStreamingConfigurations indexOfObject:self.session.videoStreamingConfiguration];
    NSAssert(idx != NSNotFound, @"Oops");
    if (0 == idx) {
        return;
    }
    PLVideoStreamingConfiguration *newStreamingConfiguration = self.videoStreamingConfigurations[idx - 1];
    [self.session reloadVideoStreamingConfiguration:newStreamingConfiguration];
    NSLog(@"自动降低了推流质量");
}

-(void)warningHostOut
{
    if(!self.anchorClose)
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLTLocalizedString(@"温馨提示", nil) message:NSLTLocalizedString(@"您的当前网络太差，请移至网络良好的地方再次开播，感谢您的支持", nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"确 定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LTMessage *message = [LTSDKHelper sendCloseLiveMessageRoomId:self.livemodel.chatRoomId];
            [self sendMessageWithMessage:message];
            [[BONSTimerQueue shareTimer] removeEcvent:@selector(timerRefresh) target:self];
        }];
        [alertController addAction:sureAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


- (void)showAlertWithMessage:(NSString *)message completion:(void (^)(void))completion
{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:NSLTLocalizedString(@"错误", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
    [controller addAction:[UIAlertAction actionWithTitle:NSLTLocalizedString(@"确定", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (completion) {
            completion();
        }
    }]];
    [self presentViewController:controller animated:YES completion:nil];
}





#pragma mark    LTChatManagerDelegate   接收mars聊天室消息
- (void)messageDidReceiveChatRoom:(NSArray *)messages
{
    for (LTMessage *message in messages) {
        if(message.chatType == LTChatTypeChatRoom)
        {
            NSLog(@"接收到聊天室消息");
            [self filterMessage:message];
        }
    }
}
-(void)sendMessageWithMessage:(LTMessage *)message
{
    if(message.chatType == LTChatTypeChatRoom)
    {
        NSLog(@"聊天室发送消息");
        message.level = 4;
        [self filterMessage:message];
    }
    [[LTClient sharedClient].chatManager sendMessage:message progress:nil completion:^(LTMessage *message, LTError *error) {
        if(message.messageType == LTMessageTypeCloseLive)
        {
            [[MTLiveApiManager manager] closeLive:self.roomid completion:^(MTError *error) {
                
            }];
        }
        NSLog(@"%@",error);
    }];
}
//处理消息
-(void)filterMessage:(LTMessage *)message
{
    
    if(![message.targetUserId isEqualToString:self.chatRoomid])
    {
        return;
    }
    switch (message.messageType) {
        case LTMessageTypeBarrage:
        {
            [self.bulletManager addCommentWith:message];
        }break;
        case LTMessageTypeLightUp:{
            [self lightenAnimation];
            self.LightCountNumber++;
        } break;
        case LTMessageTypeGift:
        {
            LTMessageGiftBody *body = (LTMessageGiftBody *)message.body;
            [self AnimationWithmodel:body Anduserinfo:message.since number:@"1"];
            if(body.animation)
            {
                [self.hugeAimationManger addAnimationWithName:body.englishTitle isFull:YES];
            }
        }break;
        case LTMessageTypeCloseLive:
        {
            [[LTClient sharedClient].chatManager removeDelegate:self];
            if(self.conteollerType == LiveControllertypeAudience)
            {
                self.finishView.liveModel = self.livemodel;
                [self.view addSubview:self.finishView];
            }else if (self.conteollerType == LiveControllertypeLive)
            {
                self.livestopView.anchorModel = self.livemodel.anchor;
                [[MTLiveApiManager manager] liveEndInfo:self.livemodel.Id completion:^(MTLiveModel *model, MTError *error) {
                   if(error == nil)
                   {
                       self.livestopView.totalCount = [NSString stringWithFormat:@"%d",model.viewerCnt];
                       self.livestopView.harvest = model.totalReceive;
                   }
                }];
                [self.view addSubview:self.livestopView];
            }
            return;
        }break;
        case LTMessageTypeRoomNormal:
        {
            
            
        }break;
        case LTMessageTypeRoomJoin:
        {
            LTUser *sendUser = message.since;
            if([sendUser.userId isEqualToString:[LTClient sharedClient].currentUser.userId])
            {
                return;
            }
        }break;
        case LTMessageTypeRoomSetManager:
        {
            LTMessageRoomOperationBody *body =(LTMessageRoomOperationBody *)message.body;
            if([body.operationUser.userId isEqualToString:[LTClient sharedClient].currentUser.userId])
            {
                [MBProgressHUD showMessage:@"主播设置了你为管理员"];
            }
        }break;
        case LTMessageTypeRoomCancelManager:
        {
            
            
        }break;
        case LTMessageTypeRoomMute:
        {
            LTMessageRoomOperationBody *body =(LTMessageRoomOperationBody *)message.body;
            if([body.operationUser.userId isEqualToString:[LTClient sharedClient].currentUser.userId])
            {
                self.inputView.isBlack = YES;
                [MBProgressHUD showMessage:@"管理员将你禁言了"];
            }
            
        }break;
        case LTMessageTypeRoomCancelMute:
        {
            LTMessageRoomOperationBody *body =(LTMessageRoomOperationBody *)message.body;
            if([body.operationUser.userId isEqualToString:[LTClient sharedClient].currentUser.userId])
            {
                self.inputView.isBlack = NO;
                [MBProgressHUD showMessage:@"管理员解除了你的禁言"];
            }
        }break;
        case LTMessageTypeRoomKickout:
        {
            LTMessageRoomOperationBody *body =(LTMessageRoomOperationBody *)message.body;
            if([body.operationUser.userId isEqualToString:[LTClient sharedClient].currentUser.userId])
            {
                [self.player stop];
                UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:@"你被管理员踢出了房间" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self CloseRoomClick:nil];
                }];
                [alterVc addAction:action1];
                [self presentViewController:alterVc animated:YES completion:nil];
                return;
            }
        }break;
        case LTMessageTypeRoomUpdateTitle:
        {
            LTMessageUpdateTitleBody *body = (LTMessageUpdateTitleBody *)message.body;
            LTUser *sendUser = message.since;
            self.livetitleLable.text = [NSString stringWithFormat:@"直播主题:%@",body.title];
            if([sendUser.userId isEqualToString:[LTClient sharedClient].currentUser.userId])
            {
                return;
            }
        }break;
        case LTMessageTypeRoomFocusHost:
        {
            
        }break;
        default:    break;
    }
    [[HMessageTool messgeTool] addMessageAndShow:message withSuccesss:^(HLiveMesssage *liveMessage, BOOL success) {
        if(success)
        {
            [self.messageViewModel.mesageArray addObject:liveMessage];
            [self.messageView reloadData];
        }
    }];
}

#pragma mark  RCIMClientReceiveMessageDelegate  接收消息

//礼物动画
-(void)AnimationWithmodel:(LTMessageGiftBody *)model Anduserinfo:(LTUser *)userinfo number:(NSString *)numberstr
{
    
    NSLog(@"view -%@,%@",self.sendgiftView.userinfo.userId,userinfo.userId);
    if(self.sendgiftView.userinfo.userId.integerValue == userinfo.userId.integerValue)
    {
        [self.sendgiftView AnimationWithmodel:model Anduserinfo:userinfo number:numberstr];
        
    }else if(self.sendgiftView1.userinfo.userId.integerValue == userinfo.userId.integerValue)
    {
        [self.sendgiftView1 AnimationWithmodel:model Anduserinfo:userinfo number:numberstr];
    }else
    {
        if(self.sendgiftView1.ishidden)
        {
            [self.sendgiftView1 AnimationWithmodel:model Anduserinfo:userinfo number:numberstr];
        }else
        {
            [self.sendgiftView AnimationWithmodel:model Anduserinfo:userinfo number:numberstr];
        }
    }
}

-(void)setLightCountNumber:(NSInteger)LightCountNumber
{
    _LightCountNumber = LightCountNumber;
    self.lightNumberView.Lightnumber = LightCountNumber;

}

-(void)dealloc
{
    [self cancleAddObserver];
    NSLog(@"dellodddddddd");
}

//私有方法
-(void)livefailedWarning:(NSString *)warningString withInfo:(NSString *)info
{
    
}


@end
